package masterjava.common.property;

import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;

import java.net.InetAddress;

/**
 * User: GKislin
 * Date: 20.02.2011
 */
public class StringConverter<T> implements IConverter<T> {
    protected final Class<T> clazz;

    static {
        register(InetAddress.class, new ConvertAdapter<InetAddress>() {
            @Override
            protected InetAddress convert(String property) throws Exception {
                return InetAddress.getByName(property);
            }
        });
    }

    public static <R> void register(final Class type, final IConverter<R> newConverter) {
        ConvertUtils.register(new Converter() {

            @Override
            public Object convert(Class type, Object value) {
                return newConverter.toValue((String) value);
            }
        }, type);
    }

    public StringConverter(Class<T> clazz) {
        this.clazz = clazz;
    }

    @Override
    public T toValue(String property) {
        if (Enum.class.isAssignableFrom(clazz)) {
            Class raw = clazz;
            return (T) Enum.valueOf(raw, property);
        }
        return (T) ConvertUtils.convert(property, clazz);
    }

    @Override
    public String toString(T value) {
        return ConvertUtils.convert(value);
    }
}
